<template>
  <div class="product-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商品列表</span>
          <div class="header-actions">
            <el-button
                type="primary"
                @click="showCrawlerManager = true"
                :icon="Setting"
            >
              爬虫管理
            </el-button>
            <el-button
                type="success"
                @click="showQuickCrawlDialog = true"
                :icon="Download"
            >
              快速爬取
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索筛选 -->
      <div class="filter-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="商品标题">
            <el-input
                v-model="searchForm.title"
                placeholder="请输入商品标题"
                clearable
                style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="产品类型">
            <el-select
                v-model="searchForm.productType"
                placeholder="请选择产品类型"
                clearable
                style="width: 150px"
            >
              <el-option label="GT" value="GT" />
              <el-option label="AI" value="AI" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否获取详情">
            <el-select
                v-model="searchForm.detailFetched"
                placeholder="请选择"
                clearable
                style="width: 120px"
            >
              <el-option label="是" :value="true" />
              <el-option label="否" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
            <el-button @click="handleReset" :icon="RefreshLeft">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 商品表格 -->
      <el-table
          :data="productStore.products"
          :loading="productStore.loading"
          style="width: 100%"
      >
        <el-table-column prop="id" label="商品ID" width="200" />
        <el-table-column prop="title" label="商品标题" width="750" show-overflow-tooltip />
        <el-table-column prop="productType" label="类型" width="80" />
        <el-table-column prop="level" label="星级" width="200">
          <template #default="{ row }">
            <el-rate
                v-model="row.level"
                disabled
                show-score
                text-color="#ff9900"
            />
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="120">
          <template #default="{ row }">
            <span class="price">￥{{ row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="detailFetched" label="详情状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.detailFetched ? 'success' : 'warning'">
              {{ row.detailFetched ? '已获取' : '未获取' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="200" />
        <el-table-column label="操作" width="400" fixed="right">
          <template #default="{ row }">
            <el-button
                type="primary"
                size="small"
                @click="viewDetail(row.id)"
                :icon="View"
            >
              查看详情
            </el-button>
            <el-button
                v-if="!row.detailFetched"
                type="success"
                size="small"
                @click="fetchDetail(row.id)"
                :icon="Download"
            >
              获取详情
            </el-button>
            <el-button
                v-if="row.detailFetched"
                type="warning"
                size="small"
                @click="openEditDialog(row)"
                :icon="Edit"
            >
              编辑
            </el-button>
            <el-button
                v-if="row.detailFetched"
                type="danger"
                size="small"
                @click="deleteProduct(row.id)"
                :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="productStore.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 快速爬取对话框 -->
    <el-dialog v-model="showQuickCrawlDialog" title="快速爬取" width="500px">
      <el-form :model="crawlForm" label-width="100px">
        <el-form-item label="关键词" required>
          <el-input v-model="crawlForm.keyword" placeholder="请输入搜索关键词，如：丽江" />
        </el-form-item>
        <el-form-item label="游玩天数">
          <el-input-number v-model="crawlForm.days" :min="1" :max="15" />
        </el-form-item>
        <el-form-item label="页码">
          <el-input-number v-model="crawlForm.pageIndex" :min="1" :max="10" />
        </el-form-item>
        <el-form-item label="每页数量">
          <el-input-number v-model="crawlForm.pageSize" :min="10" :max="100" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showQuickCrawlDialog = false">取消</el-button>
        <el-button type="primary" @click="handleQuickCrawl" :loading="crawling">
          开始爬取
        </el-button>
      </template>
    </el-dialog>

    <!-- 爬虫任务管理对话框 -->
    <el-dialog v-model="showCrawlerManager" width="90%" top="5vh">
      <CrawlerTaskManager />
    </el-dialog>

    <!-- 内容编辑弹窗 -->
    <PageContentEditor
        ref="editorDialogRef"
        v-model="editorDialogVisible"
        :edit-data="currentEditData"
        @submit="handleContentSubmit"
        @close="handleEditorClose"
    />

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useProductStore } from '@/stores/product'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Download,
  Search,
  RefreshLeft,
  View, Setting, Edit, Delete
} from '@element-plus/icons-vue'
// 导入爬虫任务管理组件
import CrawlerTaskManager from '@/components/CrawlerTaskManager.vue'
import PageContentEditor from '@/components/PageDivEditorDialog.vue'

// 编辑器弹窗相关
const editorDialogVisible = ref(false)
const currentEditData = ref(null)
const editorDialogRef = ref() // 添加弹窗组件引用

// 添加状态
const showQuickCrawlDialog = ref(false)
const showCrawlerManager = ref(false)
const crawling = ref(false)

const router = useRouter()
const productStore = useProductStore()

// 搜索表单
const searchForm = reactive({
  title: '',
  productType: '',
  detailFetched: null
})

// 快速爬取表单
const crawlForm = reactive({
  keyword: '',
  pageIndex: 1,
  days: 1,
  pageSize: 30
})

// 分页
const pagination = reactive({
  current: 1,
  size: 20
})

// 获取商品列表
const fetchProducts = async () => {
  const params = {
    page: pagination.current,
    size: pagination.size,
    ...searchForm
  }
  await productStore.fetchProducts(params)
}

// 处理内容提交
const handleContentSubmit = async (formData) => {
  try {
    const response = await productStore.updateContent(formData)
    if (response.success) {
      ElMessage.success(formData.id ? '更新成功' : '保存成功')
      editorDialogVisible.value = false
      await fetchProducts()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败：' + error.message)
  }
}

// 打开编辑对话框
const openEditDialog = (row) => {
  currentEditData.value = { ...row }
  if (editorDialogRef.value) {
    editorDialogRef.value.openDialog('', row)
  }
}

// 处理编辑器关闭
const handleEditorClose = () => {
  currentEditData.value = null
  editorDialogVisible.value = false
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchProducts()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    productType: '',
    detailFetched: null
  })
  pagination.current = 1
  fetchProducts()
}

// 分页事件
const handleSizeChange = (size) => {
  pagination.size = size
  fetchProducts()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  fetchProducts()
}

// 查看详情
const viewDetail = (id) => {
  router.push(`/products/${id}`)
}

// 获取详情
const fetchDetail = async (id) => {
  try {
    await ElMessageBox.confirm('确认获取该商品的详情页面吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })

    await productStore.fetchProductDetail(id)
    ElMessage.success('详情获取任务已提交')
    await fetchProducts() // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('获取详情失败')
    }
  }
}

const deleteProduct = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })

    const response = await productStore.deleteProduct(id)
    if (response.success) {
      ElMessage.success(response.message)
    } else {
      ElMessage.error(response.message || '删除失败')
    }

    await fetchProducts() // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 快速爬取
const handleQuickCrawl = async () => {
  if (!crawlForm.keyword) {
    ElMessage.warning('请输入关键词')
    return
  }

  crawling.value = true
  try {
    await productStore.crawlProducts(crawlForm)
    ElMessage.success('爬取任务已启动')
    showQuickCrawlDialog.value = false
    await fetchProducts() // 刷新列表
  } catch (error) {
    ElMessage.error('爬取失败')
  } finally {
    crawling.value = false
  }
}

onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.product-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .filter-section {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fafafa;
    border-radius: 4px;
  }

  .price {
    color: #f56c6c;
    font-weight: bold;
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }
}
</style>